package com.huahai.manager.websocket.disruptor;

import com.huahai.manager.websocket.model.PictureEditMessageDTO;
import com.huahai.pojo.entity.User;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import javax.annotation.PreDestroy;
import javax.annotation.Resource;

/**
 * 图片编辑事件的生产者
 *
 * @author huahai
 */
@Component
@Slf4j
public class PictureEditEventProducer {

    @Resource
    Disruptor<PictureEditEvent> pictureEditEventDisruptor;

    /**
     * 发送图片编辑事件
     * @param pictureEditMessageDTO 图片编辑消息
     * @param session websocket session
     * @param pictureId 图片 id
     * @param user 用户
     */
    public void publishEvent(PictureEditMessageDTO pictureEditMessageDTO, WebSocketSession session, Long pictureId, User user){
        // 获取 ringBuffer 环形队列
        RingBuffer<PictureEditEvent> ringBuffer = pictureEditEventDisruptor.getRingBuffer();
        // 获取下一个可用的序号
        long next = ringBuffer.next();
        // 获取该序号对应的事件对象
        PictureEditEvent pictureEditEvent = ringBuffer.get(next);
        // 设置事件对象
        pictureEditEvent.setPictureEditMessageDTO(pictureEditMessageDTO);
        pictureEditEvent.setSession(session);
        pictureEditEvent.setUser(user);
        pictureEditEvent.setPictureId(pictureId);
        // 发布事件到环形队列中
        ringBuffer.publish(next);
    }

    /**
     * 优雅停机
     */
    @PreDestroy
    public void close(){
        pictureEditEventDisruptor.shutdown();
    }
}
